﻿// Copyright 2008 Benjamin Jenks 
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may 
// not use this file except in compliance with the License. You may obtain 
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, 
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
// See the License for the specific language governing permissions and 
// limitations under the License. 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace iTunesAlbumArtFetcher.Core
{
    /// <summary>
    /// Manages fetching and cacheing Album artwork.
    /// </summary>
    public class ArtworkManager
    {
        // mapping from an album to its associated artwork
        private Dictionary<string, string> trackToArtwork= new Dictionary<string,string>();
        private Dictionary<string, string> originalUrlToArtwork= new Dictionary<string,string>();
        // set of tracks for which not to find artwork
        private HashSet<string> ignoredTracks = new HashSet<string>();
        
        public void Cache(iTunes.Track track, GImageSearch.Image image) {
            WebClient client= new WebClient();
            string tempFile= Path.GetTempFileName();
            client.DownloadFile( image.OriginalUrl, tempFile );

            this.trackToArtwork[ this.MakeKey( track ) ]= tempFile;
            this.originalUrlToArtwork[ image.OriginalUrl ]= tempFile;
        }

        public bool TryToAssociateArtwork(iTunes.Track track) {
            bool isCached= this.trackToArtwork.ContainsKey( this.MakeKey( track ) );
            if ( isCached ) { track.Artwork= this.trackToArtwork[ this.MakeKey( track ) ]; }
            return isCached;
        }

        public bool TryToAssociateArtwork(iTunes.Track track, GImageSearch.Image image) {
            string tempFile= this.originalUrlToArtwork[ image.OriginalUrl ];
            this.trackToArtwork[ this.MakeKey( track ) ]= tempFile;
            track.Artwork= tempFile;
            return tempFile != null;
        }

        public void Ignore(iTunes.Track track) {
            this.ignoredTracks.Add( this.MakeKey( track ) );
        }

        public bool IsIgnored(iTunes.Track track) {
            return this.ignoredTracks.Contains( this.MakeKey( track ) );
        }

        private string MakeKey(iTunes.Track track) {
            return track.Artist + "|" + track.Album;
        }
    }
}